<?php
// 单条查询
function find($sql)
{
    global $db;

    $result = mysqli_query($db, $sql);

    if (!$result)
    {
        echo "SQL语句执行失败：" . $sql;
        exit;
    }

    return mysqli_fetch_assoc($result);
}

// 查询所有
function all($sql)
{
    global $db;

    $result = mysqli_query($db, $sql);

    if (!$result)
    {
        echo "SQL语句执行失败：" . $sql;
        exit;
    }

    // 多条数据就是要循环
    $list = [];

    while ($data = mysqli_fetch_assoc($result))
    {
        $list[] = $data;
    }

    return $list;
}

// 新增
function add($table, $data)
{
    global $db;
    global $pre;

    $table = $table;

    $keys =  '`' . implode('`,`', array_keys($data)) . '`';

    $values = "'" . implode("','", $data) . "'";


    $sql = "INSERT INTO $table ($keys)  VALUES($values)";

    $result = mysqli_query($db, $sql);

    if (!$result)
    {
        echo "SQL语句执行失败：" . $sql;
        exit;
    }

    return mysqli_insert_id($db);
}

// 更新
function edit($table, $data, $where)
{
    global $db;
    global $pre;

    $table = $pre . $table;

    $str = '';

    foreach ($data as $key => $val)
    {
        $str .= "`$key` = '$val',";
    }

    $str = trim($str, ',');

    $sql = "UPDATE  $table  SET $str WHERE $where";

    $result = mysqli_query($db, $sql);

    if (!$result)
    {
        echo "SQL语句执行失败：" . $sql;
        exit;
    }

    return mysqli_affected_rows($db);
}

// 删除
function del($table, $where)
{
    global $db;
    global $pre;

    $table = $pre . $table;

    $sql = "DELETE FROM  $table  WHERE $where";

    $result = mysqli_query($db, $sql);

    if (!$result)
    {
        echo "SQL语句执行失败：" . $sql;
        exit;
    }

    return mysqli_affected_rows($db);
}

// function_exists — 如果给定的函数已经被定义就返回 true

if (!function_exists('ShowMsg'))
{
    /**
     * 消息提醒
     * @param string 提示消息
     */
    function ShowMsg($msg, $url = null)
    {
        $msg = $msg ?? '未知消息';

        $str = '';

        if($url)
        {
            $str = "
                <script>
                    alert('$msg');
                    location.href= '$url'
                </script>
            ";
        }
        else
        {
            $str = "
                <script>
                    alert('$msg');
                    history.go(-1)
                </script>
            ";
        }

        echo $str;
    }
}

if(!function_exists('build_randstr'))
{
    /**
     * 获得随机字符串
     * @param $len           需要的长度
     * @param $special       是否需要特殊符号
     * @return string       返回随机字符串
     */
    function build_randstr($len = 10,  $special = false)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if($special)
        {
            $chars = array_merge($chars, array(
            "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
            "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
            "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        // 获取到数组的索引值
        $charsLen = count($chars) - 1;
        // 打乱数组 shuffle — 打乱数组
        shuffle($chars);

        $str = '';

        for($i = 0; $i < $len; $i++)
        {
            $str .= $chars[random_int(0, $charsLen)]; //随机取出一位
        }

        return $str;        
    }
}

// 图片上传
if(!function_exists('upload'))
{
    function upload($name, $upload = "./assets/uploads", $type = ['jpg','png','gif','jpeg'], $size = 1048576000)
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => ''
        ];

        $file = $_FILES[$name];

        if($file) {
            // 判断上传错误码
            switch($file['error'])
            {
                case 1:
                    $result['msg'] = '上传文件超过了PHP配置文件中upload_max_filesize选项的值';
                    break;
                case 2:
                    $result['msg'] = '上传文件超过了表单中MAX_FILE_SIZE选项指定的值';
                    break;
                case 3:
                    $result['msg'] = '文件只有部分被上传';
                    break;
                case 4:
                    $result['msg'] = '没有文件被上传';
                    break;
                case 6:
                    $result['msg'] = '找不到临时文件夹';
                    break;
                case 7:
                    $result['msg'] = '文件写入失败';
                    break;
                case 8:
                    $result['msg'] = 'PHP扩展阻止文件上传';
                    break;
                default:
                    $result['msg'] = '未知上传错误';
                    break;

            }
            // 判断图片大小
            if($file['size'] > $size)
            {
                $result['msg'] = '上传文件超过了PHP配置文件中upload_max_filesize选项的值';
                return $result;
            }
            // 判断文件类型
            $types = pathinfo($file['name'], PATHINFO_EXTENSION);
            if(!in_array($types, $type))
            {
                $result['msg'] = '上传文件类型错误';
                return $result;
            }

             // 确保上传目录存在且有写入权限
            //  $upload = realpath($upload) ?: $upload; 
             if (!is_dir($upload)) {
                 if (!mkdir($upload, 0777, true)) {
                     $result['msg'] = '无法创建上传目录';
                     return $result;
                 }
             }
             if (!is_writable($upload)) {
                 $result['msg'] = '上传目录没有写入权限';
                 return $result;
             }

            //设置保存图片的名称 . build_randstr(5)
            $filename = date('YmdHis',time()) . random_int(1000,9999) . random_int(1000,9999) . '.' . $types;

            //is_uploaded_file — 检查文件是否是通过 HTTP POST 上传的
            if(is_uploaded_file($file['tmp_name']))
            {
                $newname = $upload.'/'.$filename;
                // var_dump($newname);
                // exit;
                //move_uploaded_file — 将上传的文件移动到新位置
                move_uploaded_file($file['tmp_name'], $newname);

                $result = [
                    'code' => 1,
                    'msg' => '上传成功',
                    'data' => $newname
                ];
            }
        }
        return $result;
    }
}

if (!function_exists('get_url'))
{
    /**
     * 获得当前的URL地址
     */
    function get_url()
    {
        // $url = 'http';
        // if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')
        // {
        //     $url .= 's';
        // }
        // $url .= '://';
        // $url .= $_SERVER['SERVER_NAME'];
        // $url .= $_SERVER['REQUEST_URI'];
        // return $url;

        //获取当前完整的地址
        $str = $_SERVER['PHP_SELF'] . '?';

        if ($_GET) {
            foreach($_GET as $key => $val)
            {
                if ($key != 'page') {
                    $str .= $key . '=' . $val . '&';
                }
            }
        }
        return $str;
    }
}

// 分页功能的封装方法
if (!function_exists('page'))
{
    function page($current,$count,$limit = 10,$size = 5, $class = "badoo")
    {
        $str = '<div class="'.$class.'">';

        //总页码
        $pages = ceil($count / $limit);

        if ($pages)
        {
            //获取地址
            $url = get_url();

            //判断是否是首页
            if ($current == 1)
            {
                $str .= '<span class="disabled">首&nbsp;&nbsp;页</span>';
                $str .= '<span class="disabled"><上一页</span>';
            }
            else
            {
                $str .= '<a href="'.$url.'&page=1">首&nbsp;&nbsp;页</a>';
                // 修正 URL 拼接
                $str .= '<a href="'.$url . '&page=' . ($current - 1).'"><i class="icon-arrow-left"></i>上一页</a>';
            }

            // 中间部分显示页码，取得页码范围
            if ($current <= floor($size / 2)) {
                //当前页中间位置靠左，floor()向下取整
                $start = 1;
                //如果总页数大于中间显示多少页，结束数字就是中间显示多少页的数字，否则结束数字就是总页数
                $end = $pages <= $size ? $size : $pages;
            } elseif ($current >= $pages - floor($size / 2)) { 
                //当前页中间位置靠右，总页数减去中间显示多少页就是开始数字，避免也是出现0或负数
                $start = $pages - $size + 1;
                $end = $pages;
            } else {
                $start = $current - floor($size / 2);
                $end = $current + floor($size / 2);
            }
            // 循环显示页码
            for ($i = $start; $i <= $end; $i++) {
                if ($i == $current) {
                    $str .= '<span class="current">' . $i . '</span>';
                } else {
                    $str .= '<a href="' . $url . 'page=' . $i . '">' . $i . '</a>';
                }
            }
            // 省略号的显示
            if ($start > 1) {
                $str .= '<span>...</span>';
            }
            if ($end < $pages) {
                $str .= '<span>...</span>';
            }   

            //判断是否是尾页
            if ($current == $pages)
            {
                $str .= '<span class="disabled"><下一页</span>';
                $str .= '<span class="disabled">尾页</span>';
            }
            else
            {
                $str .= '<a href="'.$url . 'page=' . ($current + 1).'"><i class="icon-arrow-right"></i>下一页</a>';
                $str .= '<a href="'.$url . 'page=' . $pages.'"><i class="icon-arrow-right"></i>尾页</a>';
            }
        }
        $str .= '</div>';
        return $str;
    }
}